<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- 用CSS实现预加载 -->
    <!-- <style>
        #preload1{
            background: url(./images/001.jpg) no-repeat -9999px -9999px;
        }
        #preload2{
            background: url(./images/002.jpg) no-repeat -9999px -9999px;
        }
        #preload3{
            background: url(./images/003.jpg) no-repeat -9999px -9999px;
        }
        #preload4{
            background: url(./images/004.jpg) no-repeat -9999px -9999px;
        }
    </style> -->
  </head>
  <body>
    <div class="box">
      <div id="preload1"></div>
      <div id="preload2"></div>
      <div id="preload3"></div>
      <div id="preload4"></div>
    </div>
    <!-- <img src="http://127.0.0.1:5500/JavaScript/JavaScript%E4%BC%98%E5%8C%96/images/001.jpg" alt=""> -->
  </body>
  <script>
    // 用Javascript实现预加载
    // 将预加载图片封装到一个函数中
    function preloader() {
      // 兼容判断
      if (document.getElementById) {
        document.getElementById("preload1").style.background =
          "url(./images/001.jpg) no-repeat -9999px -9999px";
        document.getElementById("preload2").style.background =
          "url(./images/002.jpg) no-repeat -9999px -9999px";
        document.getElementById("preload3").style.background =
          "url(./images/003.jpg) no-repeat -9999px -9999px";
        document.getElementById("preload4").style.background =
          "url(./images/004.jpg) no-repeat -9999px -9999px";
      }
    }

    // 监听页面是否加载完成，只有加载完成后，才执行预加载
    function addLoadEvent(fn) {
      var load = window.onload;
      // 判断DOM是否加载完毕 加载完成后会获得回调函数
      if (typeof window.load == "function") {
        // 页面加载完成，执行预加载
        window.onload = fn;
      } else {
        // 页面未加载完成
        window.onload = function () {
          if (load) {
            load();
          }
          fn();
        };
      }
    }

    addLoadEvent(preloader);
  </script>
</html>
